bool topologicalSort_Dfs(vector< vector<bool> > &map, vector<int> &answer) {
	stack<int> reversePostOrder;
	vector<bool> visited(map.size(), false), onStack(visited);
	vector<int> cyclePath;
	bool isCycle = false;
	for (int i = 0; i != map.size() && !isCycle; ++i) {
		vector<int> edgeFrom(map.size());
		if (!visited[i])
			dfs(map, i, reversePostOrder, visited, onStack, edgeFrom, cyclePath, isCycle);
	}
	answer.clear();
	if (isCycle) {
        return false;
	}
	while (!reversePostOrder.empty()) {
		int label = reversePostOrder.top(); reversePostOrder.pop();
		answer.push_back(label);
	}
	return true;
}

void dfs(vector< vector<bool> > &map, int v, stack<int> &reversePostOrder, vector<bool> &visited,
	vector<bool> &onStack, vector<int> &edgeFrom, vector<int> &cyclePath, bool &isCycle) {
	visited[v] = true; onStack[v] = true;
	for (int w = 0; w != map.size(); ++w) {
		if (isCycle)
			return;
		if (map[v][w]) {
			if (!visited[w]) {
				edgeFrom[v] = w;
				dfs(map, w, reversePostOrder, visited, onStack, edgeFrom, cyclePath, isCycle);
			}
			else if (onStack[w]) {
				isCycle = true;
				for (int cur = w; cur != v; cur = edgeFrom[cur])
					cyclePath.push_back(cur);
				cyclePath.push_back(v);
			}
		}
	}
	onStack[v] = false;
	reversePostOrder.push(v);
}

//
bool topologicalSort_Kahn(vector< vector<bool> > &map, vector<int> &answer) {
	queue<int> topoSortQue;
	vector<int> inDegree(map.size(), 0);
	answer.clear();
	for (int i = 0; i != map.size(); ++i) {
		for (int j = 0; j != map[i].size(); ++j)
			if (map[i][j])
				++inDegree[j];
	}
	for (int i = 0; i != inDegree.size(); ++i) {
		if (!inDegree[i])
			topoSortQue.push(i);
	}
	while (!topoSortQue.empty()) {
		int label = topoSortQue.front(); topoSortQue.pop();
		answer.push_back(label);
		for (int i = 0; i != map.size(); ++i) {
			if (map[label][i] && --inDegree[i] == 0)
				topoSortQue.push(i);
		}
	}
	if (answer.size() < map.size()) {
		answer.clear(); return false;
	}
	else
		return true;
}